import React, { useState } from 'react';
import { useRequest } from 'ahooks';
import { Card, Button, Table, Form, Input, Space, Typography, Tooltip } from 'antd';
import { PlusCircleFilled } from '@ant-design/icons';
import PateoAuthButtons from '@/common/PateoAuthButtons/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import {
  addModule,
  /* deleteModule, */ editModule,
  fetchData,
} from '@/services/intelligent/module';
import ModuleModal from './ModuleModal';
import MaskText, { formatFn, emailExp } from '@/components/MaskText';

const DEFAULT_FORM_VALUES = () => ({
  name: '',
  email: '',
});

// @connect(state => ({
//   extendForm: state.extendForm,
//   menu: state.menu,
// }))

export default () => {
  const [formValues, setFormValues] = useState(DEFAULT_FORM_VALUES());
  const [pagination, setPagination] = useState({
    pageNo: 1,
    pageSize: 10,
  });

  const [form] = Form.useForm();

  const { data, run, loading } = useRequest(
    () => fetchData(Object.assign(formValues, pagination)),
    {
      refreshDeps: [formValues, pagination],
    },
  );

  const [formData, setFormData] = useState<any>(null);
  const [visible, setVisible] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const handleCancel = () => {
    setVisible(false);
    setFormData(null);
    readOnly && setReadOnly(false);
  };

  const handleFinish = async (value: { name: string; description?: string; email?: string[] }) => {
    const _value = {
      ...value,
      email: value.email?.join(','),
    };

    if (formData) {
      await editModule(Object.assign({ uuid: formData.uuid }, _value));
    } else {
      await addModule(_value);
    }
    handleCancel();
    run();
  };

  const handleReset = () => {
    form.resetFields();
    setFormValues(DEFAULT_FORM_VALUES());
  };

  // const handleDelete = (uuid: string) => {
  //   deleteModule(uuid).then(() => run());
  // };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_text: any, _record: any, index: number) => index + 1,
    },
    {
      title: '模块名称',
      dataIndex: 'name',
    },
    {
      title: '模块说明',
      dataIndex: 'description',
      render: (text: string) => (
        <Typography.Text style={{ maxWidth: 280 }} ellipsis={{ tooltip: text }}>
          {text}
        </Typography.Text>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      render(val: any) {
        if (!val) return '--';
        if (typeof val === 'string') {
          let emails = val
            .split(',')
            .map(item => formatFn({ val: item, regExp: emailExp, length: 4 }));
          return <Tooltip title={val}  >{emails.join(',')}</Tooltip>
        }
        return val;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render(val: any) {
        return <MaskText text={val} type="name" />;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render(val: any) {
        return <MaskText text={val} type="name" />;
      },
    },
    {
      title: '操作',
      dataIndex: '操作',
      fixed: 'right',
      render: (_text: any, record: any) => {
        const btns = [
          {
            title: '编辑',
            key: 'edit',
            onConfirm: () => {
              setFormData(record);
              setVisible(true);
            },
          },
          // {
          //   title: '删除',
          //   key: 'delete',
          //   Popconfirm: true,
          //   message: '确认删除吗?',
          //   onConfirm: () => {
          //     handleDelete(record.uuid);
          //   },
          // },
          {
            title: '详情',
            key: 'des',
            onConfirm: () => {
              // 邮箱脱敏
               let email = record.email
              .split(',')
              .map(item => formatFn({ val: item, regExp: emailExp, length: 4 }));
              setFormData({...record, email: email.join(',')});
              setVisible(true);
              setReadOnly(true);
            },
          },
        ];
        return <PateoAuthButtons authStr="groupManagement" btns={btns} />;
      },
    },
  ];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    total: data?.pagination?.total || 0,
    page: pagination.pageNo,
    pageSize: pagination.pageSize,
    showTotal: () => (
      <span>共&nbsp;{data?.pagination === undefined ? 0 : data.pagination.total}&nbsp;条</span>
    ),
  };
  return (
    <div>
      <Card bordered={false}>
        <Form form={form} layout="inline" onFinish={setFormValues}>
          <Form.Item label="模块名称" name="name">
            <Input placeholder="请输入模块名称" />
          </Form.Item>
          <Form.Item label="邮箱" name="email">
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Space size={12} style={{ marginLeft: 'auto' }}>
            <Button type="primary" htmlType="submit" size="small">
              查询
            </Button>
            <Button htmlType="button" size="small" onClick={handleReset}>
              重置
            </Button>
          </Space>
        </Form>
      </Card>
      <Card className={styles.standardTable}>
        <Button icon={<PlusCircleFilled />} onClick={() => setVisible(true)}>
          配置模块
        </Button>
        <Table
          style={{ marginTop: 12 }}
          size={'small'}
          loading={loading}
          rowKey={record => record.uuid}
          dataSource={data?.list}
          columns={columns}
          scroll={{ x: 'max-content' }}
          pagination={paginationProps}
          onChange={({ current, pageSize }) =>
            setPagination({ pageNo: current || 1, pageSize: pageSize || 10 })
          }
        />
      </Card>

      {visible && (
        <ModuleModal
          readOnly={readOnly}
          formData={formData}
          onCancel={handleCancel}
          onFinish={handleFinish}
        />
      )}
    </div>
  );
};
